<template>
  <div class="china-map-container">
    <div class="map-controls">
      <el-button @click="testConnection" type="primary">测试连接</el-button>
      <el-button @click="clearConnections" type="warning">清除连接</el-button>
      <div class="info-text">点击两个省份进行连接</div>
    </div>

    <div ref="mapContainer" class="map-wrapper"></div>

    <div class="map-info">
      <div class="info-title">调试信息</div>
      <div class="info-content">
        <div class="info-item">
          <span class="info-label">地图模式：</span>
          <span class="info-value">{{ mapDataLoaded ? '真实地图' : '散点图' }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">连接数：</span>
          <span class="info-value">{{ connections.length }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">选中数：</span>
          <span class="info-value">{{ selectedProvinces.length }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

const mapContainer = ref(null)
let chart = null
let mapDataLoaded = false

const selectedProvinces = ref([])
const connections = ref([])

// 省份数据
const provinceData = [
  { name: '北京', value: 2189, adcode: '110000', coords: [116.4, 39.9] },
  { name: '天津', value: 1386, adcode: '120000', coords: [117.2, 39.1] },
  { name: '河北', value: 7556, adcode: '130000', coords: [114.5, 38.0] },
  { name: '山西', value: 3718, adcode: '140000', coords: [112.5, 37.8] },
  { name: '内蒙古', value: 2520, adcode: '150000', coords: [111.7, 40.8] },
  { name: '辽宁', value: 4359, adcode: '210000', coords: [123.4, 41.8] },
  { name: '吉林', value: 2407, adcode: '220000', coords: [125.3, 43.8] },
  { name: '黑龙江', value: 3773, adcode: '230000', coords: [126.6, 45.7] },
  { name: '上海', value: 2487, adcode: '310000', coords: [121.4, 31.2] },
  { name: '江苏', value: 8505, adcode: '320000', coords: [118.7, 32.0] },
  { name: '浙江', value: 6540, adcode: '330000', coords: [120.1, 30.2] },
  { name: '安徽', value: 6127, adcode: '340000', coords: [117.2, 31.8] },
  { name: '福建', value: 4188, adcode: '350000', coords: [119.3, 26.0] },
  { name: '江西', value: 4519, adcode: '360000', coords: [115.8, 28.6] },
  { name: '山东', value: 10170, adcode: '370000', coords: [117.0, 36.6] },
  { name: '河南', value: 9883, adcode: '410000', coords: [113.6, 34.7] },
  { name: '湖北', value: 5927, adcode: '420000', coords: [114.3, 30.5] },
  { name: '湖南', value: 6644, adcode: '430000', coords: [112.9, 28.2] },
  { name: '广东', value: 12684, adcode: '440000', coords: [113.2, 23.1] },
  { name: '广西', value: 5037, adcode: '450000', coords: [108.3, 22.8] },
  { name: '海南', value: 1008, adcode: '460000', coords: [110.3, 20.0] },
  { name: '重庆', value: 3205, adcode: '500000', coords: [106.5, 29.5] },
  { name: '四川', value: 8375, adcode: '510000', coords: [104.0, 30.6] },
  { name: '贵州', value: 3856, adcode: '520000', coords: [106.7, 26.5] },
  { name: '云南', value: 4721, adcode: '530000', coords: [102.7, 25.0] },
  { name: '西藏', value: 365, adcode: '540000', coords: [91.1, 29.6] },
  { name: '陕西', value: 3954, adcode: '610000', coords: [108.9, 34.2] },
  { name: '甘肃', value: 2502, adcode: '620000', coords: [103.8, 36.0] },
  { name: '青海', value: 594, adcode: '630000', coords: [101.7, 36.6] },
  { name: '宁夏', value: 728, adcode: '640000', coords: [106.2, 38.4] },
  { name: '新疆', value: 2585, adcode: '650000', coords: [87.6, 43.8] }
]

// 加载地图数据
const loadMapData = async () => {
  try {
    const response = await fetch('/china.json')
    const data = await response.json()
    echarts.registerMap('china', data)
    mapDataLoaded = true
    console.log('地图数据加载成功')
    initMap()
  } catch (error) {
    console.error('加载地图数据失败:', error)
    mapDataLoaded = false
    initMap()
  }
}

// 初始化地图
const initMap = () => {
  if (!mapContainer.value) return

  chart = echarts.init(mapContainer.value)
  updateMapData()

  window.addEventListener('resize', handleResize)
}

// 更新地图数据
const updateMapData = () => {
  if (!chart) return

  let option

  if (mapDataLoaded) {
    // 真实地图模式
    option = {
      backgroundColor: '#F0F8FF',
      title: {
        text: '中国人口分布地图 - 调试版本',
        left: 'center',
        top: 20,
        textStyle: {
          fontSize: 20,
          fontWeight: 'bold',
          color: '#1565C0'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: (params) => {
          if (params.seriesType === 'map') {
            return `${params.name}<br/>人口：${params.value} 万人<br/>点击选择进行连接`
          }
          return `${params.name}`
        }
      },
      geo: {
        map: 'china',
        roam: true,
        zoom: 1.2,
        itemStyle: {
          areaColor: '#E8F4FD',
          borderColor: '#fff',
          borderWidth: 1.5
        },
        emphasis: {
          itemStyle: {
            areaColor: '#7BC2F1'
          }
        }
      },
      series: []
    }

    // 添加地图数据
    option.series.push({
      name: '人口分布',
      type: 'map',
      map: 'china',
      roam: true,
      zoom: 1.2,
      label: {
        show: true,
        fontSize: 10,
        color: '#333',
        fontWeight: 'bold'
      },
      data: provinceData.map(item => ({
        name: item.name,
        value: item.value
      })),
      itemStyle: {
        borderColor: '#fff',
        borderWidth: 1.5
      }
    })

  } else {
    // 散点图模式
    option = {
      backgroundColor: '#F0F8FF',
      title: {
        text: '中国人口分布地图 - 调试版本',
        left: 'center',
        top: 20,
        textStyle: {
          fontSize: 20,
          fontWeight: 'bold',
          color: '#1565C0'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: (params) => {
          if (params.data) {
            return `${params.data[3]}<br/>人口：${params.data[2]} 万人<br/>点击选择进行连接`
          }
          return `${params.name}`
        }
      },
      xAxis: {
        type: 'value',
        show: false,
        min: 70,
        max: 140
      },
      yAxis: {
        type: 'value',
        show: false,
        min: 15,
        max: 55
      },
      series: []
    }

    // 添加散点数据
    option.series.push({
      name: '人口分布',
      type: 'scatter',
      coordinateSystem: 'cartesian2d',
      symbolSize: (data) => {
        return Math.sqrt(data[2]) / 4 + 8
      },
      itemStyle: {
        color: (params) => {
          const value = params.data[2]
          if (value > 5000) return '#1565C0'
          if (value > 2000) return '#2E9EE5'
          if (value > 1000) return '#7BC2F1'
          if (value > 500) return '#B8E0F7'
          return '#E8F4FD'
        },
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: true,
        position: 'top',
        formatter: (params) => {
          return `${params.data[3]}\n${params.data[2]}万人`
        },
        fontSize: 10,
        color: '#333',
        fontWeight: 'bold'
      },
      data: provinceData.map(item => [
        item.coords[0],
        item.coords[1],
        item.value,
        item.name
      ])
    })
  }

  // 添加连接线（简化版本用于调试）
  connections.value.forEach((conn, index) => {
    const coords1 = getProvinceCoords(conn.from.name)
    const coords2 = getProvinceCoords(conn.to.name)

    console.log(`添加连接线 ${index}:`, conn.from.name, '->', conn.to.name)
    console.log('坐标1:', coords1)
    console.log('坐标2:', coords2)

    if (mapDataLoaded) {
      // 真实地图模式
      // 添加测试点
      option.series.push({
        name: `测试点${index}_1`,
        type: 'scatter',
        coordinateSystem: 'geo',
        symbolSize: 30,
        itemStyle: {
          color: '#FF0000',
          borderColor: '#fff',
          borderWidth: 3
        },
        zlevel: 100,
        data: [coords1]
      })

      option.series.push({
        name: `测试点${index}_2`,
        type: 'scatter',
        coordinateSystem: 'geo',
        symbolSize: 30,
        itemStyle: {
          color: '#00FF00',
          borderColor: '#fff',
          borderWidth: 3
        },
        zlevel: 100,
        data: [coords2]
      })

      // 添加连接线
      option.series.push({
        name: `连接线${index}`,
        type: 'lines',
        coordinateSystem: 'geo',
        zlevel: 50,
        lineStyle: {
          width: 8,
          color: '#FF6B35',
          curveness: 0.2,
          opacity: 1
        },
        effect: {
          show: true,
          period: 6,
          trailLength: 0.8,
          symbol: 'circle',
          symbolSize: 20,
          color: '#FFD700'
        },
        data: [{
          coords: [coords1, coords2]
        }]
      })

    } else {
      // 散点图模式
      option.series.push({
        name: `测试点${index}_1`,
        type: 'scatter',
        coordinateSystem: 'cartesian2d',
        symbolSize: 30,
        itemStyle: {
          color: '#FF0000',
          borderColor: '#fff',
          borderWidth: 3
        },
        data: [coords1]
      })

      option.series.push({
        name: `测试点${index}_2`,
        type: 'scatter',
        coordinateSystem: 'cartesian2d',
        symbolSize: 30,
        itemStyle: {
          color: '#00FF00',
          borderColor: '#fff',
          borderWidth: 3
        },
        data: [coords2]
      })

      option.series.push({
        name: `连接线${index}`,
        type: 'lines',
        coordinateSystem: 'cartesian2d',
        symbolSize: 20,
        zlevel: 50,
        lineStyle: {
          width: 8,
          color: '#FF6B35',
          curveness: 0.2,
          opacity: 1
        },
        effect: {
          show: true,
          period: 6,
          trailLength: 0.8,
          symbol: 'circle',
          symbolSize: 20,
          color: '#FFD700'
        },
        data: [{
          coords: [coords1, coords2]
        }]
      })
    }
  })

  // 添加选中标记
  selectedProvinces.value.forEach(province => {
    const coords = getProvinceCoords(province.name)

    if (mapDataLoaded) {
      option.series.push({
        name: '选中省份',
        type: 'scatter',
        coordinateSystem: 'geo',
        symbolSize: 25,
        itemStyle: {
          color: '#FF00FF',
          borderColor: '#fff',
          borderWidth: 3
        },
        zlevel: 200,
        data: [coords]
      })
    } else {
      option.series.push({
        name: '选中省份',
        type: 'scatter',
        coordinateSystem: 'cartesian2d',
        symbolSize: 25,
        itemStyle: {
          color: '#FF00FF',
          borderColor: '#fff',
          borderWidth: 3
        },
        data: [coords]
      })
    }
  })

  console.log('最终option配置:', option)
  chart.setOption(option)

  // 点击事件
  chart.off('click')
  chart.on('click', (params) => {
    console.log('点击事件:', params)

    let province = null
    if (params.seriesType === 'map' && params.data) {
      province = params.data
    } else if (params.seriesType === 'scatter' && params.data) {
      province = {
        name: params.data[3],
        value: params.data[2]
      }
    }

    if (province) {
      handleProvinceClick(province)
    }
  })
}

// 获取省份坐标
const getProvinceCoords = (name) => {
  const normalizeName = (name) => {
    return name.replace(/省|市|自治区|特别行政区/g, '')
  }

  const province = provinceData.find(p => normalizeName(p.name) === normalizeName(name))
  return province ? province.coords : [110, 35]
}

// 测试连接
const testConnection = () => {
  console.log('测试连接功能')

  // 模拟创建北京到上海的连接
  const beijing = provinceData.find(p => p.name === '北京')
  const shanghai = provinceData.find(p => p.name === '上海')

  if (beijing && shanghai) {
    connections.value.push({
      from: beijing,
      to: shanghai
    })
    console.log('测试连接已创建: 北京 -> 上海')
    updateMapData()
  }
}

// 处理省份点击
const handleProvinceClick = (clickedProvinceData) => {
  console.log('点击省份:', clickedProvinceData.name)

  // 查找省份对象（去除"省"字进行匹配）
  const normalizeName = (name) => {
    return name.replace(/省|市|自治区|特别行政区/g, '')
  }

  const clickedName = normalizeName(clickedProvinceData.name)
  const province = provinceData.find(p => normalizeName(p.name) === clickedName)
  console.log('标准化后的点击名称:', clickedName)

  if (!province) {
    console.error('未找到省份:', clickedProvinceData.name)
    return
  }

  // 检查是否已选中（使用标准化名称进行比较）
  const existingIndex = selectedProvinces.value.findIndex(p => normalizeName(p.name) === clickedName)

  if (existingIndex !== -1) {
    // 取消选中
    selectedProvinces.value.splice(existingIndex, 1)
    console.log('取消选中:', province.name)
  } else {
    // 添加到选中列表
    selectedProvinces.value.push(province)
    console.log('选中:', province.name, '当前选中数量:', selectedProvinces.value.length)

    // 如果有两个选中省份，创建连接
    if (selectedProvinces.value.length === 2) {
      createConnection(selectedProvinces.value[0], selectedProvinces.value[1])
    }
  }

  updateMapData()
}

// 创建连接
const createConnection = (province1, province2) => {
  console.log('创建连接:', province1.name, '->', province2.name)

  connections.value.push({
    from: province1,
    to: province2
  })

  // 清空选中省份
  selectedProvinces.value = []

  updateMapData()
}

// 清除连接
const clearConnections = () => {
  console.log('清除连接...')
  connections.value = []
  selectedProvinces.value = []

  // 强制清除图表并重新绘制
  if (chart) {
    chart.clear()
    updateMapData()
  }
}

// 处理窗口大小变化
const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}

// 组件挂载时初始化
onMounted(() => {
  loadMapData()
})

// 组件卸载前清理
onBeforeUnmount(() => {
  if (chart) {
    chart.dispose()
  }
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.china-map-container {
  width: 100%;
  height: 100vh;
  position: relative;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
}

.china-map-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
    radial-gradient(circle at 20% 50%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
    radial-gradient(circle at 80% 80%, rgba(255, 182, 193, 0.3) 0%, transparent 50%);
  pointer-events: none;
}

.map-controls {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
  display: flex;
  align-items: center;
  gap: 15px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 15px 20px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.info-text {
  color: #666;
  font-size: 14px;
  font-weight: 500;
}

.map-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 1;
}

.map-info {
  position: absolute;
  top: 20px;
  right: 20px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  z-index: 1000;
  min-width: 240px;
}

.info-title {
  font-weight: bold;
  margin-bottom: 15px;
  color: #1565C0;
  font-size: 14px;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  color: #666;
  font-size: 13px;
  font-weight: 500;
}

.info-value {
  color: #1565C0;
  font-weight: bold;
  font-size: 13px;
  text-align: right;
}

:deep(.el-button) {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>